package forkJoin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

public class ForkJoinSum {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
        long arr[] = {2, 11, 3, 5, 17, 22, 13, 17};
        ForkJoinTask<List<Long>> forkJoinTask = forkJoinPool.submit(new SumTask(arr, 0, arr.length));
        System.out.println(JSONObject.toJSONString(forkJoinTask.get()));
    }

    private static class SumTask extends RecursiveTask<List<Long>>{
        private long[] arr;
        private int from;
        private int to;

        public SumTask(long[] arr, int from, int to){
            this.arr = arr;
            this.from = from;
            this.to = to;
        }

        @Override
        protected List<Long> compute(){
            List<Long> result = new ArrayList<>();
            if(to - from <= 2){
                long sum = 0;
                for (int i = from; i < to; i++) {
                    sum += (arr[i]);
                }
                result.add(sum );
                return result;
            }
            int middle = (from + to) /2;
            SumTask left = new SumTask(arr, from, middle);
            SumTask right = new SumTask(arr, middle, to);
            try {
                result.addAll(left.fork().get());
                result.addAll(right.fork().get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

            return result;
        }

    }
}
